#include <iostream>
using std::cout;
using std::endl;
using std::string;

template <class Type>
struct MyDefaultDelter
{
    void operator()(Type * type) const
    {
        delete type;
    }
};

struct Myfpcloser
{
    void operator()(FILE * fp)
    {
        if(fp) {
            fclose(fp);
            cout << " >> fclose(fp)" << endl;
        }
    }
};

//自定义的智能指针 
template <class Type, class Deleter = MyDefaultDelter<Type>>
class RAII
{
public:
    RAII(Type * p)
    : _p(p)
    //, _deleter() //不写的时候，也会自动调用相应类型
    {}              //的默认构造函数初始化_deleter对象

    ~RAII() {
        if(_p) {
            //delete _p;//确定的使用deleter表达式
            _deleter(_p);//不确定的情况下，传一个函数过来
            _p = nullptr;
        }
    }

    Type * operator->()
    {   return _p;  }

    Type & operator*()
    {   return *_p; }

    Type * get() const {    return _p;  }

    //从类中删除该函数, 就不能执行赋值或者复制
    RAII(const RAII &) = delete;
    RAII & operator=(const RAII&) = delete;

private:
    Type * _p;//默认情况下托管的是堆空间的资源
    Deleter _deleter;
};

class Point
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {   cout << "Point(int,int)" << endl;    }

    ~Point()
    {   cout << "~Point()" << endl; }  

    void print() const 
    {
        cout << "(" << _ix
             << "," << _iy
             << ")" << endl;
    }

private:
    int _ix;
    int _iy;
};

void test0()
{
    //智能指针的用法
    RAII<Point> raii(new Point(1, 2));
    raii->print();
    (*raii).print();
}

void test1()
{
    Point * pt = new Point(1, 2);
    pt->print();
    MyDefaultDelter<Point> del;
    del(pt);
}

void test2()
{
    cout << "raii" << endl;
    RAII<FILE, Myfpcloser> raii(fopen("test.txt", "a+"));   
    string msg("this is a test\n");
    fwrite(msg.c_str(), 1, msg.size(), raii.get());
}


int main()
{
    /* test0(); */
    /* test1(); */
    test2();
    return 0;
}

